package com.jiuyuan.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-16 05:52
 **/

@Controller
public class KaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation("验证码")
    @GetMapping(value = "/kaptcha",produces = "image/jpg")
    public void kaptcha(HttpServletRequest req, HttpServletResponse resp){
        //设置请求头输出位image类型
        resp.setContentType("image/jpg");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
        resp.setDateHeader("Expires", 0);

        //构造输出验证码
        String text = defaultKaptcha.createText();
        System.out.println(text);
        req.getSession().setAttribute("kaptcha",text);
        BufferedImage image = defaultKaptcha.createImage(text);
        try(ServletOutputStream outputStream = resp.getOutputStream();) {
            ImageIO.write(image,"jpg",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
